<template>
  <div>
    <div>
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="标题">
          <el-input ref="title" v-model="state.params.title" placeholder="文章标题"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="state.params.status" placeholder="状态">
            <el-option label="已发布" value="Published"/>
            <el-option label="草稿" value="Draft"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :loading="state.isLoading" type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="button-container">
      <el-button :loading="state.isLoading" type="primary" @click="showAddDrawer"><i class="el-icon-plus"/> 新 增
      </el-button>
      <el-button circle icon="el-icon-s-unfold" @click="state.showCatalogTree=true"/>
    </div>
    <div>
      <el-table ref="articleTable" :data="state.articleList" :header-cell-style="{background:'#eef1f6',color:'#606266'}" stripe
                style="width: 100%">
        <el-table-column type="selection" width="55"/>
        <el-table-column label="ID" prop="id" width="80"/>
        <el-table-column label="标题" prop="title" width="200"/>
        <el-table-column label="状态" prop="status" width="100"/>
        <el-table-column label="分类" prop="catalog_info.name"/>
        <el-table-column :formatter="datetimeFormatter" label="修改时间" prop="modified_at"/>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-popconfirm cancelButtonText='取消' confirmButtonText='删除' icon="el-icon-info" iconColor="red"
                           title="确定删除该文章吗？" @confirm="deleteArticle(scope.$index,scope.row)">
              <template #reference>
                <el-button size="small" type="text">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
            <el-button size="small" type="text" @click.prevent="showEditDrawer(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button v-if="scope.row.status==='草稿'" size="small" type="text"
                       @click.prevent="publishArticle(scope.$index, scope.row)">
              发布
            </el-button>
            <el-button v-else size="small" type="text"
                       @click.prevent="offlineArticle(scope.$index, scope.row)">
              下线
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <div class="pagination">
      <el-pagination :page-size="10" :total="state.total" background
                     layout="prev, pager, next"></el-pagination>
    </div>
  </div>
  <EditArticle
      :article-id="state.articleId"
      :visible="state.showDrawer"
      @close="handleCloseDrawer"
  />
  <CatalogTree
      :visible="state.showCatalogTree"
      @close="state.showCatalogTree=false"
  />
</template>

<script lang="ts">
import {defineComponent, reactive} from "vue";
import {Article, ArticleArray, ArticleParams} from "../../types";
import {getArticleList, remoteDeleteArticle, remoteOfflineArticle, remotePublishArticle} from "../../api/service";
import {timestampToTime} from "../../utils";
import {ElMessage} from "element-plus";
import EditArticle from "../../components/EditArticle.vue";
import CatalogTree from "../../components/CatalogTree.vue";

export default defineComponent({
  name: "Article",
  components: {CatalogTree, EditArticle},
  setup: function () {
    const state = reactive({
      articleList: [] as Array<Article>,
      params: {
        title: undefined,
        status: undefined,
        tags: undefined,
        catalog: undefined,
        page: 1,
        page_size: 10,
      } as ArticleParams,
      isLoading: false,
      total: 0,
      showDrawer: false,
      articleId: 0,
      showCatalogTree: false,
    });

    const handleSearch = async (): Promise<void> => {
      state.isLoading = true;
      try {
        const data: ArticleArray = await getArticleList(state.params);
        state.isLoading = false;
        state.articleList = data.results;
        state.total = data.count
      } catch (e) {
        console.error(e)
        state.isLoading = false;
      }
    };

    const publishArticle = async (index: number, row: Article) => {
      try {
        await remotePublishArticle(row.id)
        ElMessage({
          message: "发布成功！",
          type: "success",
        });
        await handleSearch()
      } catch (e) {
        console.error(e)
      }
    }

    const offlineArticle = async (index: number, row: Article) => {
      try {
        await remoteOfflineArticle(row.id)
        ElMessage({
          message: "下线成功！",
          type: "success",
        });
        await handleSearch()
      } catch (e) {
        console.error(e)
      }
    }

    const deleteArticle = async (index: number, row: Article) => {
      await remoteDeleteArticle(row.id);
      ElMessage({
        message: "删除成功！",
        type: "success",
      });
      await handleSearch()
    }

    const datetimeFormatter = (row: Article, column: number, cellValue: string, index: number) => {
      return timestampToTime(cellValue, true);
    }

    handleSearch()

    const handleCloseDrawer = (isOk: boolean) => {
      state.showDrawer = false
      if (isOk) {
        handleSearch()
      }
    }
    return {
      state,
      handleSearch,
      datetimeFormatter,
      deleteArticle,
      handleCloseDrawer,
      publishArticle,
      offlineArticle
    }
  },
  mounted() {
    this.$refs.title.focus()
  },
  methods: {
    showEditDrawer(index: number, row: Article) {
      this.$refs.articleTable.setCurrentRow(row)
      this.state.showDrawer = true;
      this.state.articleId = row.id
    },
    showAddDrawer() {
      this.state.showDrawer = true;
      this.state.articleId = 0;
    }
  }
})
</script>

<style scoped>
.pagination {
  text-align: right;
  margin-top: 12px;
}
</style>